package com.feixiang.feixiangagent.app;
import com.feixiang.feixiangagent.advisor.MyLoggerAdvisor;
import com.feixiang.feixiangagent.advisor.ReReadingAdvisor;
import com.feixiang.feixiangagent.chatmemory.FileBasedChatMemory;
import com.feixiang.feixiangagent.chatmemory.RedisChatMemory;
import com.feixiang.feixiangagent.rag.LoveAppRagCustomAdvisorFactory;
import com.feixiang.feixiangagent.rag.QueryRewriter;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.QuestionAnswerAdvisor;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.ai.chat.client.advisor.api.Advisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.InMemoryChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.tool.ToolCallback;
import org.springframework.ai.tool.ToolCallbackProvider;
import org.springframework.ai.tool.ToolCallbacks;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;
import java.util.List;

import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;
import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_RETRIEVE_SIZE_KEY;

@Component
@Slf4j
public class LoveApp {
    //系统提示词
    private static final String SYSTEM_PROMPT = "扮演深耕恋爱心理领域的专家。开场向用户表明身份，告知用户可倾诉恋爱难题。" +
            "围绕单身、恋爱、已婚三种状态提问：单身状态询问社交圈拓展及追求心仪对象的困扰；" +
            "恋爱状态询问沟通、习惯差异引发的矛盾；已婚状态询问家庭责任与亲属关系处理的问题。" +
            "引导用户详述事情经过、对方反应及自身想法，以便给出专属解决方案。";
    //定义一个ChatClient
    private final ChatClient chatClient;
    public LoveApp(ChatModel dashscopeChatModel, RedisTemplate<String, Object> redisTemplate) {
        //1.初始化基于文件的会话记录
//        String dir = System.getProperty("user.dir") + "/temp/chat-memory";
//        ChatMemory chatMemory = new FileBasedChatMemory(dir);
        //2.初始化基于内存存储会话记录
        //ChatMemory chatMemory = new InMemoryChatMemory();
        //3.初始化基于redis存储会话记录
        ChatMemory chatMemory = new RedisChatMemory(redisTemplate);
        chatClient = ChatClient.builder(dashscopeChatModel)
                .defaultSystem(SYSTEM_PROMPT)
                .defaultAdvisors(
                        new MessageChatMemoryAdvisor(chatMemory),
                        //自定义日志拦截器
                        new MyLoggerAdvisor()
                        //自定义推理增强 Advisor 可按需开启
                        // new ReReadingAdvisor()
                )
                .build();
    }
    /**
     * AI 基础多轮对话
     *
     * @param message
     * @param chatId
     * @return
     */
    public String doChat(String message, String chatId) {
        ChatResponse chatResponse = chatClient
                .prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .call()
                .chatResponse();
        String content = chatResponse.getResult().getOutput().getText();
        System.out.println(content);
        return content;
    }

    /**
     * 流式多轮对话
     * @param message
     * @param chatId
     * @return
     */
    public Flux<String> doChatByStream(String message, String chatId) {
        Flux<String> content = chatClient
                .prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .stream()
                .content();
        return content;
    }

    record LoveReport(String title, List<String> suggestions) {
    }

    /**
     * AI 实战结构化输出
     *
     * @param message
     * @param chatId
     * @return
     */
    public LoveReport doChatWithReport(String message, String chatId) {
        LoveReport loveReport = chatClient
                .prompt()
                .system(SYSTEM_PROMPT + "每次对话后都要生成恋爱结果，标题为{用户名}的恋爱报告，内容为建议列表")
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .call()
                .entity(LoveReport.class);
        log.info("LoveReport: {}", loveReport);
        return loveReport;

    }

    //知识库问答功能
    @Resource
    private VectorStore loveAppVectorStore;
    //private VectorStore pgVectorVectorStore;

    @Resource
    private Advisor loveAppRagCloudAdvisor;
    //重写器
    @Resource
    private QueryRewriter queryRewriter;

    /**
     * 知识问答
     *
     * @param message
     * @param chatId
     * @return
     */
    public String doChatWithRag(String message, String chatId) {
        //查询重写，使用改写后的
        String rewriteMessage = queryRewriter.doQueryRewrite(message);
        ChatResponse chatResponse = chatClient
                .prompt()
                .user(rewriteMessage)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                //开启日志，便于观察效果
                .advisors(new MyLoggerAdvisor())
                //应用RAG开启知识库搜索
                .advisors(new QuestionAnswerAdvisor(loveAppVectorStore))
                //RAG开启云知识库增强
                //.advisors(loveAppRagCloudAdvisor)
                //自定义RAG增强服务 Advisor（文档查询器 +上下文增强）
//                .advisors(
//                        LoveAppRagCustomAdvisorFactory.createLoveAppRagCustomAdvisor(loveAppVectorStore,"分类结果.md")
//                )
                .call()
                .chatResponse();
        String content = chatResponse.getResult().getOutput().getText();
        System.out.println(content);
        return content;
    }
    // 工具调用功能
    @Resource
    private ToolCallback[] allTools;
    /**
     * AI 工具调用
     *
     * @param message
     * @param chatId
     * @return
     */
    public String doChatWithTools(String message, String chatId) {
      ChatResponse  chatResponse   = chatClient
                .prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                //开启日志，便于观察效果
                .advisors(new MyLoggerAdvisor())
                .tools(allTools)
                .call()
                .chatResponse();
        String content = chatResponse.getResult().getOutput().getText();
        log.info("content: {}", content);
        return content;

    }

    //AI 调用MCP
    @Resource
    private ToolCallbackProvider mcpToolCallbackProvider;
    public String doChatWithMCP(String message, String chatId) {
        ChatResponse  chatResponse   = chatClient
                .prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                //开启日志，便于观察效果
                .advisors(new MyLoggerAdvisor())
                .tools(mcpToolCallbackProvider)
                .call()
                .chatResponse();
        String content = chatResponse.getResult().getOutput().getText();
        log.info("content: {}", content);
        return content;

    }


}
